package com.test;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author xingdongyang
 * @date 2020/8/12
 */
public class RandomPwd {

    /**
     * 密码可能会包含的字符集合
     */
    private static char[] fullCharSource = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '{', '}', '|', ':', '"', '<', '>', '?', ';', '\'', ',', '.', '/', '-', '=', '`'};
    /**
     * 将可能的密码集合长度
     */
    private static int fullCharLength = fullCharSource.length;

    /**
     * maxLength：生成的字符串的最大长度
     */
    public static void generate(int maxLength) throws FileNotFoundException {
        //计数器，多线程时可以对其加锁，当然得先转换成Integer类型。
        int counter = 0;
        StringBuilder builder = new StringBuilder();

        PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("D://密码字典.txt"), StandardCharsets.UTF_8));

        while (builder.toString().length() <= maxLength) {
            builder = new StringBuilder(maxLength * 2);
            int tmpCounter = counter;
            //10进制转换成26进制
            while (tmpCounter >= fullCharLength) {
                //获得低位
                builder.insert(0, fullCharSource[tmpCounter % fullCharLength]);
                tmpCounter = tmpCounter / fullCharLength;
                //处理进制体系中只有10没有01的问题，在穷举里面是可以存在01的
                tmpCounter--;
            }
            //最高位
            builder.insert(0, fullCharSource[tmpCounter]);
            counter++;

            pw.write(builder.toString() + "\n");
            System.out.println(builder.toString());
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        generate(20);
    }

//
//    private static Set<String> result = new HashSet<>();
//
//    public static void main(String[] args) {
//        // 随机生成密码文件 6-20的密码文件
//        char[] a = {'a', 'b', 'b'};
//        permutation(a, 0, 2);
//        System.out.println(result);
//    }
//
//    private static void permutation(char[] a, int from, int to) {
//        if (a == null || from > to || from < 0) {
//            return;
//        }
//        if (from == to) {
//            result.add(String.valueOf(a));
//        }
//        for (int i = from; i <= to; i++) {
//            swap(a, i, from);
//            permutation(a, from + 1, to);
//            swap(a, i, from);
//        }
//    }
//
//    private static void swap(char[] a, int left, int right) {
//        char temp = a[left];
//        a[left] = a[right];
//        a[right] = temp;
//    }
}
